package com.newshub.app.ui.video

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.newshub.app.R
import com.newshub.app.data.model.VideoNews

class VideoNewsAdapter(private val onItemClick: (VideoNews) -> Unit) :
    ListAdapter<VideoNews, VideoNewsAdapter.VideoViewHolder>(VideoDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder {
        // 使用自定义布局或更合适的系统布局
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_video_news, parent, false)
        return VideoViewHolder(view)
    }

    override fun onBindViewHolder(holder: VideoViewHolder, position: Int) {
        val videoNews = getItem(position)
        holder.bind(videoNews)
    }

    inner class VideoViewHolder(itemView: View) :
        RecyclerView.ViewHolder(itemView) {
        
        private val coverImage: ImageView = itemView.findViewById(R.id.coverImage)
        private val title: TextView = itemView.findViewById(R.id.title)
        private val source: TextView = itemView.findViewById(R.id.source)
        private val playCount: TextView = itemView.findViewById(R.id.playCount)
        private val duration: TextView = itemView.findViewById(R.id.duration)

        fun bind(videoNews: VideoNews) {
            try {
                // 加载视频封面图
                Glide.with(itemView)
                    .load(videoNews.cover)
                    .apply(RequestOptions.bitmapTransform(RoundedCorners(8)))
                    .placeholder(android.R.drawable.ic_menu_gallery)
                    .error(android.R.drawable.ic_menu_gallery)
                    .into(coverImage)

                // 设置标题
                title.text = videoNews.title

                // 设置来源/时间
                source.text = videoNews.ptime

                // 设置播放量（格式化数字）
                playCount.text = "${formatPlayCount(videoNews.playCount)} 播放"

                // 设置视频时长
                duration.text = formatDuration(videoNews.duration.toInt())

                // 设置点击事件
                itemView.setOnClickListener { onItemClick(videoNews) }
            } catch (e: Exception) {
                // 捕获任何异常，确保不会导致列表项崩溃
                if (title != null) title.text = "视频信息加载失败"
            }
        }
        
        // 格式化播放量，将Long转换为友好显示格式
        private fun formatPlayCount(count: Long): String {
            return when {
                count >= 10000 -> {
                    String.format("%.1f万", count / 10000.0)
                }
                count >= 1000 -> {
                    String.format("%.1f千", count / 1000.0)
                }
                else -> {
                    count.toString()
                }
            }
        }
        
        private fun formatDuration(seconds: Int): String {
            val hours = seconds / 3600
            val minutes = (seconds % 3600) / 60
            val remainingSeconds = seconds % 60

            return if (hours > 0) {
                String.format("%02d:%02d:%02d", hours, minutes, remainingSeconds)
            } else {
                String.format("%02d:%02d", minutes, remainingSeconds)
            }
        }
    }

    // DiffUtil回调
    class VideoDiffCallback : DiffUtil.ItemCallback<VideoNews>() {
        override fun areItemsTheSame(oldItem: VideoNews, newItem: VideoNews): Boolean {
            return oldItem.url == newItem.url
        }

        override fun areContentsTheSame(oldItem: VideoNews, newItem: VideoNews): Boolean {
            return oldItem == newItem
        }
    }
}